import 'package:stacked/stacked.dart';
import 'package:vista/shared/models/challenge_submission.dart';
import 'package:vista/shared/models/theme_challenge.dart';
import 'package:vista/shared/models/user_frame.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/theme_challenge_service.dart';

/// 主题挑战列表视图模型
/// 管理主题挑战列表页面的数据和状态
class ThemeChallengeListViewModel extends BaseViewModel {
  final ThemeChallengeService _themeChallengeService;
  final AuthFocus _authFocus;

  ThemeChallengeListViewModel(this._themeChallengeService, this._authFocus);

  ThemeChallenge? _currentChallenge;
  ThemeChallenge? get currentChallenge => _currentChallenge;

  List<ChallengeSubmission> _submissions = [];
  List<ChallengeSubmission> get submissions => _submissions;

  Map<String, UserFrame> _userMap = {};
  UserFrame? getUserById(String userId) => _userMap[userId];

  Map<String, bool> _likedMap = {}; // 存储每个投稿的点赞状态
  Map<String, int> _likeCountMap = {}; // 存储每个投稿的点赞数量

  bool isLiked(String submissionId) => _likedMap[submissionId] ?? false;
  int getLikeCount(String submissionId) => _likeCountMap[submissionId] ?? 0;

  /// 初始化数据
  Future<void> initialize() async {
    setBusy(true);
    try {
      await _loadCurrentChallenge();
      await _loadSubmissions();
      await _loadUsers();
    } finally {
      setBusy(false);
    }
  }

  /// 加载当前挑战
  Future<void> _loadCurrentChallenge() async {
    _currentChallenge = await _themeChallengeService.getCurrentChallenge();
    notifyListeners();
  }

  /// 加载投稿列表
  Future<void> _loadSubmissions() async {
    if (_currentChallenge == null) {
      _submissions = [];
      notifyListeners();
      return;
    }

    _submissions = await _themeChallengeService.getSubmissionsByChallenge(
      _currentChallenge!.id,
    );
    await _loadLikeStatuses();
    notifyListeners();
  }

  /// 加载点赞状态
  Future<void> _loadLikeStatuses() async {
    final currentUser = await _authFocus.getCurrentUser();
    if (currentUser == null) {
      // 如果未登录，所有投稿都未点赞
      for (var submission in _submissions) {
        _likedMap[submission.id] = false;
        _likeCountMap[submission.id] = await _themeChallengeService
            .getLikeCount(submission.id);
      }
      return;
    }

    for (var submission in _submissions) {
      _likedMap[submission.id] = await _themeChallengeService.isLiked(
        submission.id,
        currentUser.id,
      );
      _likeCountMap[submission.id] = await _themeChallengeService.getLikeCount(
        submission.id,
      );
    }
  }

  /// 加载用户信息
  Future<void> _loadUsers() async {
    final users = await _authFocus.getUsers();
    _userMap = {for (var user in users) user.id: user};
    notifyListeners();
  }

  /// 提交挑战投稿
  Future<void> submitSubmission(String imagePath) async {
    if (_currentChallenge == null) {
      return;
    }

    final currentUser = await _authFocus.getCurrentUser();
    if (currentUser == null) {
      return;
    }

    setBusy(true);
    try {
      await _themeChallengeService.submitChallenge(
        challengeId: _currentChallenge!.id,
        authorId: currentUser.id,
        image: imagePath,
      );
      await _loadSubmissions(); // 刷新列表
    } finally {
      setBusy(false);
    }
  }

  /// 切换点赞状态
  Future<void> toggleLike(String submissionId) async {
    final currentUser = await _authFocus.getCurrentUser();
    if (currentUser == null) {
      return;
    }

    setBusy(true);
    try {
      if (_likedMap[submissionId] == true) {
        await _themeChallengeService.unlikeSubmission(
          submissionId,
          currentUser.id,
        );
        _likedMap[submissionId] = false;
        _likeCountMap[submissionId] = (_likeCountMap[submissionId] ?? 1) - 1;
      } else {
        await _themeChallengeService.likeSubmission(
          submissionId,
          currentUser.id,
        );
        _likedMap[submissionId] = true;
        _likeCountMap[submissionId] = (_likeCountMap[submissionId] ?? 0) + 1;
      }
      notifyListeners();
    } finally {
      setBusy(false);
    }
  }

  /// 增加访问次数
  Future<void> incrementViewCount(String submissionId) async {
    await _themeChallengeService.incrementViewCount(submissionId);
    // 更新本地数据
    final index = _submissions.indexWhere((s) => s.id == submissionId);
    if (index != -1) {
      final submission = _submissions[index];
      _submissions[index] = ChallengeSubmission(
        id: submission.id,
        challengeId: submission.challengeId,
        authorId: submission.authorId,
        image: submission.image,
        viewCount: submission.viewCount + 1,
        timestamp: submission.timestamp,
      );
      notifyListeners();
    }
  }

  /// 刷新数据
  Future<void> refresh() async {
    await initialize();
  }

  /// 删除投稿
  Future<void> deleteSubmission(String submissionId) async {
    await _themeChallengeService.deleteSubmission(submissionId);
    // 重新加载投稿列表
    await _loadSubmissions();
  }
}
